package com.qf.commerce.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.commerce.common.dto.DealerDto;
import com.qf.commerce.common.vo.DealerVo;
import com.qf.commerce.entity.Dealer;
import com.qf.commerce.exception.ControllerException;
import com.qf.commerce.exception.DaoException;
import com.qf.commerce.exception.ServiceException;
import com.qf.commerce.mapper.DealerMapper;
import com.qf.commerce.resp.ResponseStatus;
import com.qf.commerce.service.DealerService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/*
 * @author 358
 * @since JDK 1.8
 * @data 2023/9/13 10:48
 */

@Service
public class DealerServiceImpl implements DealerService {

    @Resource
    private DealerMapper dealerMapper;

    @Override
    public Dealer selectByPrimaryKey(Integer dealerId) {
        return dealerMapper.selectByPrimaryKey(dealerId);
    }

    @Override
    public int updateByPrimaryKeySelective(DealerDto dealerDto) {
        Dealer dealer = new Dealer();
        if (ObjectUtils.isEmpty(dealer) || ObjectUtils.isEmpty(dealerDto)) {
            throw new ServiceException(ResponseStatus.DATA_ERROR);
        }
        BeanUtils.copyProperties(dealerDto, dealer);
        dealer.setStatus(1);
        return dealerMapper.updateByUserId(dealer);
    }


    @Override
    public PageInfo<DealerVo> selectListPage(Integer page, Integer size) {
        return PageHelper.startPage(page, size).doSelectPageInfo(() -> dealerMapper.selectAll());
    }

    @Override
    public Integer applyDealer(DealerDto dealerDto) {
        if (dealerMapper.countByUserId(dealerDto.getUserId()) > 0) {
            throw new ControllerException(ResponseStatus.DATA_ERROR);
        }
        Dealer dealer = new Dealer();
        if (ObjectUtils.isEmpty(dealer) || ObjectUtils.isEmpty(dealerDto)) {
            throw new ControllerException(ResponseStatus.DATA_ERROR);
        }
        BeanUtils.copyProperties(dealerDto, dealer);
        dealer.setStatus(1);
        return dealerMapper.insert(dealer);
    }

    @Override
    public Integer agreeDealerApply(Integer dealerId) {
        int num = dealerMapper.updateStatusById(dealerId, 2);
        if (num > 0) {
            return num;
        } else throw new DaoException(ResponseStatus.SYS_ERROR);
    }

    @Override
    public Integer disagreeDealerApply(Integer dealerId) {
        int num = dealerMapper.updateStatusById(dealerId, 3);
        if (num > 0) {
            return num;
        } else throw new DaoException(ResponseStatus.SYS_ERROR);
    }

    @Override
    public Integer deleteById(Integer dealerId) {
        int num = dealerMapper.updateStatusById(dealerId, 0);
        if (num > 0) {
            return num;
        } else throw new DaoException(ResponseStatus.SYS_ERROR);
    }

}
